<template>
  <a-modal title-align="start" title="设置任务执行人" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="550">
    <div>请选择任务执行人：</div>

    <div class="mt10">
      <div class="sel-item-box" v-for="(value, key) in showViewData" :key="key">
        <div class="title">{{ typeMap[key] }}</div>
        <div class="box">
          <div style="margin-top: 5px" v-for="(item, index) in value" :key="index">
            <a-space class="common-text">
              <div class="label">{{ item.name }}：</div>
              <div>
                <a-select v-model="item.executer.id" @change="handleUserChange($event, item)" allow-search allow-clear style="width: 260px" placeholder="请选择">
                  <a-option v-for="(user, index) of userList" :key="index" :value="user.id" :label="user.userName"></a-option>
                </a-select>
              </div>
              <div>
                <a-button size="small" class="gray-outline" @click="setCurType(item)">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </div>
            </a-space>
          </div>
        </div>
      </div>
    </div>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="loading" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { defineComponent, ref, computed, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getOrganizesUser } from '@/api/system'
  import { agreeTakeTask, grabTask, getTaskConfigByTaskType, updateTaskItemExcuter } from '@/api/task'
  import _ from 'lodash-es'
  let props = defineProps(['modelValue', 'ids', 'apiType', 'taskType', 'list'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })

  const typeMap = {
    NEW_PRODUCT_PICTURE: '新品套图',
    QUICK_FIX_PICTURE: '快速修图',
    ORIGINAL_PICTURE: '原图',
    SHOOT_VIDEO: '拍摄视频',
  }

  const imgTypeMap = {
    MAIN: '主图',
    PANORAMA: '全景图',
    SPECIAL: '特写图',
    SIZE: '尺寸图',
    MODEL: '模特图',
    POSTER: '海报图',
  }

  let userId = ref([])
  let loading = ref(false)
  let userList: any = ref([])
  let allUser: any = ref([])
  let form: any = ref({})
  let showViewData: any = ref({})

  const getUSerList = async () => {
    let params = {
      depart: false,
      needRole: false,
      pageNum: 1,
      pageSize: 1000,
    }
    const res: any = await getOrganizesUser(params)
    if (res) {
      let arr = res.data.records || []
      allUser.value = arr.map((e: any) => {
        e.name = e.userName
        return e
      })
    }
    // 不要接单人员相关配置
    userList.value = allUser.value
    // getTaskConfig()
  }

  const handleUserChange = (id: any, info: any) => {
    let userInfo = userList.value.find((item: any) => item.id == id)
    if (userInfo) info.executer.name = userInfo.userName
  }

  const setCurType = (info: any) => {
    if (!info.executer.id) return
    let arr: any = []
    for (const key in showViewData.value) {
      showViewData.value[key].forEach((e: any) => {
        arr.push(e)
      })
    }
    let index = arr.findIndex((item: any) => `${item.taskType}_${item.name}` == `${info.taskType}_${info.name}`)
    arr.forEach((e: any, i: number) => {
      if (i > index) {
        e.executer = _.cloneDeep(info.executer)
      }
    })
  }

  const submit = async () => {
    let newArr: any = []
    props.list.forEach((e: any) => {
      let obj: any = {
        id: e.id,
      }
      if (e.type == 'NEW_PRODUCT_PICTURE') {
        // obj.newProductPicTask = {
        //   windowPicList: _.cloneDeep(e.newProductPicTask.windowPicList),
        // }
        obj.newProductPicTask = _.cloneDeep(e.newProductPicTask)
        if (e.newProductPicTask.hasNoOriginalPic) {
          if (e.newProductPicTask.outOriginalType == 'REAL_SHOOT') {
            let item = showViewData.value[e.type].find((e: any) => e.name == '原图（拍摄）')
            if (item && item.executer.id) {
              obj.newProductPicTask.originalPicExecuter = _.cloneDeep(item?.executer) || null
            }
            // else {
            //   obj.newProductPicTask.originalPicExecuter = null
            // }
          } else {
            let item = showViewData.value[e.type].find((e: any) => e.name == '原图（渲染）')
            if (item && item.executer.id) {
              obj.newProductPicTask.originalPicExecuter = _.cloneDeep(item?.executer) || null
            }
            // else {
            //   obj.newProductPicTask.originalPicExecuter = null
            // }
            // obj.newProductPicTask.originalPicExecuter = _.cloneDeep(item?.executer) || null
          }
        }
        obj.newProductPicTask.windowPicList.map((ell: any) => {
          let item = showViewData.value[e.type].find((el: any) => ell.busType == el.type)
          if (item && item.executer.id) {
            ell.executer = _.cloneDeep(item?.executer) || null
          }
          // else {
          //   ell.executer = null
          // }
          // ell.executer = _.cloneDeep(item?.executer) || null
          return e
        })
        newArr.push(obj)
      }
      if (e.type == 'ORIGINAL_PICTURE') {
        // obj.originalPicTask = {}
        obj.originalPicTask = _.cloneDeep(e.originalPicTask)
        if (e.originalPicTask.outOriginalType == 'REAL_SHOOT') {
          let item = showViewData.value[e.type].find((e: any) => e.name == '原图（拍摄）')
          // obj.originalPicTask.originalPicExecuter = _.cloneDeep(item?.executer) || null
          if (item && item.executer.id) {
            obj.originalPicTask.originalPicExecuter = _.cloneDeep(item?.executer) || null
          }
          // else {
          //   obj.originalPicTask.originalPicExecuter = null
          // }
        } else {
          let item = showViewData.value[e.type].find((e: any) => e.name == '原图（渲染）')
          if (item && item.executer.id) {
            obj.originalPicTask.originalPicExecuter = _.cloneDeep(item?.executer) || null
          }
          // else {
          //   obj.originalPicTask.originalPicExecuter = null
          // }
          // obj.originalPicTask.originalPicExecuter = _.cloneDeep(item?.executer) || null
        }
        newArr.push(obj)
      }

      if (e.type == 'SHOOT_VIDEO') {
        // obj.shootViedoTask = {}
        obj.shootViedoTask = _.cloneDeep(e.shootViedoTask)
        if (e.shootViedoTask.outOriginalType == 'REAL_SHOOT') {
          let item = showViewData.value[e.type].find((e: any) => e.name == '原图（拍摄）')
          // obj.shootViedoTask.originalVideoExecuter = _.cloneDeep(item?.executer) || null
          if (item && item.executer.id) {
            obj.shootViedoTask.originalVideoExecuter = _.cloneDeep(item?.executer) || null
          }
          // else {
          //   obj.shootViedoTask.originalVideoExecuter = null
          // }
        } else {
          let item = showViewData.value[e.type].find((e: any) => e.name == '原图（渲染）')
          // obj.shootViedoTask.originalVideoExecuter = _.cloneDeep(item?.executer) || null
          if (item && item.executer.id) {
            obj.shootViedoTask.originalVideoExecuter = _.cloneDeep(item?.executer) || null
          }
          // else {
          //   obj.shootViedoTask.originalVideoExecuter = null
          // }
        }
        newArr.push(obj)
      }

      if (e.type == 'QUICK_FIX_PICTURE') {
        // obj.quickFixPicTask = {}
        obj.quickFixPicTask = _.cloneDeep(e.quickFixPicTask)
        if (e.quickFixPicTask.addBigPosterAttRemark) {
          let item = showViewData.value[e.type].find((e: any) => e.name == 'A+大海报')
          // obj.quickFixPicTask.addBigPosterExecuter = _.cloneDeep(item?.executer) || null
          if (item && item.executer.id) {
            obj.quickFixPicTask.addBigPosterExecuter = _.cloneDeep(item?.executer) || null
          }
          // else {
          //   obj.quickFixPicTask.addBigPosterExecuter = null
          // }
        }
        if (e.quickFixPicTask.addSmallPosterAttRemark) {
          let item = showViewData.value[e.type].find((e: any) => e.name == 'A+小海报')
          // obj.quickFixPicTask.addSmallPosterExecuter = _.cloneDeep(item?.executer) || null
          if (item && item.executer.id) {
            obj.quickFixPicTask.addSmallPosterExecuter = _.cloneDeep(item?.executer) || null
          }
          // else {
          //   obj.quickFixPicTask.addSmallPosterExecuter = null
          // }
        }
        if (e.quickFixPicTask.fixPicRemark) {
          let item = showViewData.value[e.type].find((e: any) => e.name == '改图')
          // obj.quickFixPicTask.fixPicExecuter = _.cloneDeep(item?.executer) || null
          if (item && item.executer.id) {
            obj.quickFixPicTask.fixPicExecuter = _.cloneDeep(item?.executer) || null
          }
          // else {
          //   obj.quickFixPicTask.fixPicExecuter = null
          // }
        }
        newArr.push(obj)
      }
    })

    // let params = {
    //   list: newArr,
    // }
    try {
      loading.value = true
      const res: any = await updateTaskItemExcuter(newArr)
      if (res) {
        Message.success('设置任务执行人成功')
        emits('save')
        showvisible.value = false
      }
    } catch (error) {}
    loading.value = false
  }

  // 根据任务类型获取接单配置
  const getTaskConfig = async () => {
    let res: any = await getTaskConfigByTaskType({ taskType: props.taskType })
    if (res?.data?.takeUserList[0]) {
      userList.value = res.data.takeUserList
    } else {
      userList.value = allUser.value
    }
  }

  const setData = () => {
    props.list.forEach((e: any) => {
      if (!Object.keys(showViewData.value).includes(e.type)) {
        showViewData.value[e.type] = []
      }
    })
    // 当showViewData有这种类型的时候找到里面的子项去重合并处理
    if (Object.hasOwn(showViewData.value, 'NEW_PRODUCT_PICTURE')) {
      let arr = props.list.filter((e: any) => e.type == 'NEW_PRODUCT_PICTURE')
      let newArr: any = []
      arr.forEach((e: any) => {
        // 根据是否有原图判断，没有原图就不会有拍摄和渲染选择的地方
        if (e.newProductPicTask.hasNoOriginalPic) {
          // 如果是真实拍摄就显示拍摄，否则显示渲染
          if (e.newProductPicTask?.outOriginalType == 'REAL_SHOOT') {
            let obj = {
              name: '原图（拍摄）',
              taskId: e.id,
              taskType: 'NEW_PRODUCT_PICTURE',
              executer: {
                id: null,
                name: null,
              },
            }

            // 只有一条数据的时候回显
            if (props.list.length == 1 && e.newProductPicTask?.originalPicExecuter?.id) {
              obj.executer = _.cloneDeep(e.newProductPicTask.originalPicExecuter)
            }
            newArr.push(obj)
          } else {
            let obj = {
              name: '原图（渲染）',
              taskId: e.id,
              taskType: 'NEW_PRODUCT_PICTURE',
              executer: {
                id: null,
                name: null,
              },
            }
            // 只有一条数据的时候回显
            if (props.list.length == 1 && e.newProductPicTask?.originalPicExecuter?.id) {
              obj.executer = _.cloneDeep(e.newProductPicTask.originalPicExecuter)
            }
            newArr.push(obj)
          }
        }
        // 橱窗图选项
        let windowPicList = e.newProductPicTask?.windowPicList || []
        windowPicList.forEach((item: any) => {
          let obj = {
            name: imgTypeMap[item.busType],
            taskId: e.id,
            taskType: 'NEW_PRODUCT_PICTURE',
            type: item.busType,
            executer: {
              id: null,
              name: null,
            },
          }
          // 只有一条数据的时候回显
          if (props.list.length == 1 && item?.executer?.id) {
            obj.executer = _.cloneDeep(item.executer)
          }
          newArr.push(obj)
        })
      })
      showViewData.value.NEW_PRODUCT_PICTURE = uniqueArray(newArr, 'name')
    }

    if (Object.hasOwn(showViewData.value, 'ORIGINAL_PICTURE')) {
      let arr = props.list.filter((e: any) => e.type == 'ORIGINAL_PICTURE')
      let newArr: any = []
      arr.forEach((e: any) => {
        if (e.originalPicTask?.outOriginalType == 'REAL_SHOOT') {
          let obj = {
            name: '原图（拍摄）',
            taskId: e.id,
            taskType: 'ORIGINAL_PICTURE',
            executer: {
              id: null,
              name: null,
            },
          }
          // 只有一条数据的时候回显
          if (props.list.length == 1 && e.originalPicTask?.originalPicExecuter?.id) {
            obj.executer = _.cloneDeep(e.originalPicTask.originalPicExecuter)
          }
          newArr.push(obj)
        } else {
          let obj = {
            name: '原图（渲染）',
            taskId: e.id,
            taskType: 'ORIGINAL_PICTURE',
            executer: {
              id: null,
              name: null,
            },
          }
          // 只有一条数据的时候回显
          if (props.list.length == 1 && e.originalPicTask?.originalPicExecuter?.id) {
            obj.executer = _.cloneDeep(e.originalPicTask.originalPicExecuter)
          }
          newArr.push(obj)
        }
      })
      showViewData.value.ORIGINAL_PICTURE = uniqueArray(newArr, 'name')
    }

    if (Object.hasOwn(showViewData.value, 'QUICK_FIX_PICTURE')) {
      let arr = props.list.filter((e: any) => e.type == 'QUICK_FIX_PICTURE')
      let newArr: any = []
      arr.forEach((e: any) => {
        if (e.quickFixPicTask.addBigPosterAttRemark) {
          let obj = {
            name: 'A+大海报',
            taskId: e.id,
            taskType: 'QUICK_FIX_PICTURE',
            executer: {
              id: null,
              name: null,
            },
          }
          // 只有一条数据的时候回显
          if (props.list.length == 1 && e.quickFixPicTask?.addBigPosterExecuter?.id) {
            obj.executer = _.cloneDeep(e.quickFixPicTask.addBigPosterExecuter)
          }
          newArr.push(obj)
        }
        if (e.quickFixPicTask.addSmallPosterAttRemark) {
          let obj = {
            name: 'A+小海报',
            taskId: e.id,
            taskType: 'QUICK_FIX_PICTURE',
            executer: {
              id: null,
              name: null,
            },
          }
          // 只有一条数据的时候回显
          if (props.list.length == 1 && e.quickFixPicTask?.addSmallPosterExecuter?.id) {
            obj.executer = _.cloneDeep(e.quickFixPicTask.addSmallPosterExecuter)
          }
          newArr.push(obj)
        }
        if (e.quickFixPicTask.fixPicRemark) {
          let obj = {
            name: '改图',
            taskId: e.id,
            taskType: 'QUICK_FIX_PICTURE',
            executer: {
              id: null,
              name: null,
            },
          }
          // 只有一条数据的时候回显
          if (props.list.length == 1 && e.quickFixPicTask?.fixPicExecuter?.id) {
            obj.executer = _.cloneDeep(e.quickFixPicTask.fixPicExecuter)
          }
          newArr.push(obj)
        }
      })
      showViewData.value.QUICK_FIX_PICTURE = uniqueArray(newArr, 'name')
    }

    if (Object.hasOwn(showViewData.value, 'SHOOT_VIDEO')) {
      let arr = props.list.filter((e: any) => e.type == 'SHOOT_VIDEO')
      let newArr: any = []
      arr.forEach((e: any) => {
        if (e.shootViedoTask?.outOriginalType == 'REAL_SHOOT') {
          let obj = {
            name: '原图（拍摄）',
            taskId: e.id,
            taskType: 'SHOOT_VIDEO',
            executer: {
              id: null,
              name: null,
            },
          }
          // 只有一条数据的时候回显
          if (props.list.length == 1 && e.shootViedoTask?.originalVideoExecuter?.id) {
            obj.executer = _.cloneDeep(e.shootViedoTask?.originalVideoExecuter)
          }
          newArr.push(obj)
        } else {
          let obj = {
            name: '原图（渲染）',
            taskId: e.id,
            taskType: 'SHOOT_VIDEO',
            executer: {
              id: null,
              name: null,
            },
          }
          // 只有一条数据的时候回显
          if (props.list.length == 1 && e.shootViedoTask?.originalVideoExecuter?.id) {
            obj.executer = _.cloneDeep(e.shootViedoTask?.originalVideoExecuter)
          }
          newArr.push(obj)
        }
      })
      showViewData.value.SHOOT_VIDEO = uniqueArray(newArr, 'name')
    }

    console.log(showViewData.value)
  }

  const uniqueArray = (list: any, key: string) => {
    return list.filter((item: any, index: any, self: any) => {
      return index === self.findIndex((i: any) => i[key] === item[key])
    })
  }

  // 当只有一个任务的时候回显

  onMounted(() => {
    getUSerList()
    setData()
    console.log(props.list)
  })
</script>

<style lang="less" scoped>
  .common-text {
    font-size: 12px;
    color: #a39999;
  }

  .sel-item-box {
    .title {
      font-size: 14px;
    }
    .box {
      // padding-left: 10px;
      .label {
        width: 90px;
        text-align: right;
      }
    }
  }
</style>
